<!DOCTYPE html>



  


<html class="theme-next pisces use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/blog/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/blog/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/blog/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/blog/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/blog/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/blog/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/blog/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="笔试常见问题汇总," />





  <link rel="alternate" href="/blog/atom.xml" title="伏窗尾的猫" type="application/atom+xml" />






<meta name="description" content="小感慨　　艰辛找工作的旅程终于结束了，记录下来的一些常见问题也是给了自己很大的帮助，不过还是没有更新完遇见的问题，偷了点懒，现在没有心理压力了应该能很好的完善这一篇博文，希望能够给读者带来更好的帮助。笔试的题目就不赘述了，毕竟一板一眼写就好了，但是很多时候是面试给我们带来了困难，例如优化算法，以及很细节的一些知识，都需要去深入学习，思维的作用远远超越了实现，这也是作为在校生最后一次面试得来的体会吧">
<meta name="keywords" content="笔试常见问题汇总">
<meta property="og:type" content="article">
<meta property="og:title" content="笔试常见问题汇总">
<meta property="og:url" content="http://eidolon_x.gitee.io/blog/2018/10/31/网络编程问题汇总/index.html">
<meta property="og:site_name" content="伏窗尾的猫">
<meta property="og:description" content="小感慨　　艰辛找工作的旅程终于结束了，记录下来的一些常见问题也是给了自己很大的帮助，不过还是没有更新完遇见的问题，偷了点懒，现在没有心理压力了应该能很好的完善这一篇博文，希望能够给读者带来更好的帮助。笔试的题目就不赘述了，毕竟一板一眼写就好了，但是很多时候是面试给我们带来了困难，例如优化算法，以及很细节的一些知识，都需要去深入学习，思维的作用远远超越了实现，这也是作为在校生最后一次面试得来的体会吧">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="http://eidolon_x.gitee.io/blog//eidolon_x.gitee.io/blog/2018/10/31/网络编程问题汇总/三次握手.png">
<meta property="og:image" content="http://eidolon_x.gitee.io/blog//eidolon_x.gitee.io/blog/2018/10/31/网络编程问题汇总/四次挥手.png">
<meta property="og:image" content="http://eidolon_x.gitee.io/blog//eidolon_x.gitee.io/blog/2018/10/31/网络编程问题汇总/高级内存分析.png">
<meta property="og:image" content="http://eidolon_x.gitee.io/blog//eidolon_x.gitee.io/blog/2018/10/31/网络编程问题汇总/OSI.png">
<meta property="og:updated_time" content="2021-01-18T07:27:02.905Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="笔试常见问题汇总">
<meta name="twitter:description" content="小感慨　　艰辛找工作的旅程终于结束了，记录下来的一些常见问题也是给了自己很大的帮助，不过还是没有更新完遇见的问题，偷了点懒，现在没有心理压力了应该能很好的完善这一篇博文，希望能够给读者带来更好的帮助。笔试的题目就不赘述了，毕竟一板一眼写就好了，但是很多时候是面试给我们带来了困难，例如优化算法，以及很细节的一些知识，都需要去深入学习，思维的作用远远超越了实现，这也是作为在校生最后一次面试得来的体会吧">
<meta name="twitter:image" content="http://eidolon_x.gitee.io/blog//eidolon_x.gitee.io/blog/2018/10/31/网络编程问题汇总/三次握手.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/blog/',
    scheme: 'Pisces',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":true,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://eidolon_x.gitee.io/blog/2018/10/31/网络编程问题汇总/"/>





  <title>笔试常见问题汇总 | 伏窗尾的猫</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/blog/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">伏窗尾的猫</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/blog/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/blog/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/blog/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/blog/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://eidolon_x.gitee.io/blog/blog/2018/10/31/网络编程问题汇总/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="喵呜">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/blog/images/1.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="伏窗尾的猫">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">笔试常见问题汇总</h1>
        

        <div class="post-meta">
		
			<i class="fa fa-thumb-tack"></i>
			<font color=green>置顶</font>
			<span class="post-meta-divider">|</span>
		
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-10-31T13:34:25+08:00">
                2018-10-31
              </time>
            

            
              <span class="post-meta-divider">|</span>
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-check-o"></i>
              </span>
              
                <span class="post-meta-item-text">更新于&#58;</span>
              
              <time title="更新于" itemprop="dateModified" datetime="2021-01-18T15:27:02+08:00">
                2021-01-18
              </time>
            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blog/categories/学习之路/" itemprop="url" rel="index">
                    <span itemprop="name">学习之路</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          
             <span id="/blog/2018/10/31/网络编程问题汇总/" class="leancloud_visitors" data-flag-title="笔试常见问题汇总">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">热度&#58;</span>
               
                 <span class="leancloud-visitors-count"></span>
				 <span>℃<span>
             </span>
          

          

		  
			  <span class="post-meta-divider">|</span>
			  <span id="busuanzi_value_page_pv"></span>次阅读
		  
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h2 id="小感慨"><a href="#小感慨" class="headerlink" title="小感慨"></a>小感慨</h2><p>　　艰辛找工作的旅程终于结束了，记录下来的一些常见问题也是给了自己很大的帮助，不过还是没有更新完遇见的问题，偷了点懒，现在没有心理压力了应该能很好的完善这一篇博文，希望能够给读者带来更好的帮助。笔试的题目就不赘述了，毕竟一板一眼写就好了，但是很多时候是面试给我们带来了困难，例如优化算法，以及很细节的一些知识，都需要去深入学习，思维的作用远远超越了实现，这也是作为在校生最后一次面试得来的体会吧。</p>
<h2 id="网络编程的常见问题"><a href="#网络编程的常见问题" class="headerlink" title="网络编程的常见问题"></a>网络编程的常见问题</h2><h3 id="1、TCP和UDP的区别。"><a href="#1、TCP和UDP的区别。" class="headerlink" title="1、TCP和UDP的区别。"></a>1、TCP和UDP的区别。</h3><hr>
<p>这是一个超级常见的问题，只要考网络编程就会有，但是实际上想说全比较难，建议写成两行，对比观看就很清楚。</p>
<p>TCP：面向连接的可靠的字节流服务。用户数据稳定，有序的进行传输，占用资源也多。（关键词，连接，可靠，字节流，稳定有序，占资源）    　　　　</p>
<p>UDP:无连接，不可靠的用户数据报服务。数据尽可能的高效发送，会丢包，数据传输也可能无序。（关键词，无连接，不可靠，数据报，高效无序，资源损耗少）</p>
<h3 id="2、多线程是怎么实现同步的。"><a href="#2、多线程是怎么实现同步的。" class="headerlink" title="2、多线程是怎么实现同步的。"></a>2、多线程是怎么实现同步的。</h3><hr>
<p>这个问题可能是简答题（事件，信号量，互斥锁，），也可能是一个编程题，编程题最常见的就是写两个线程实现交替打印奇数和偶数。就以这个作为例子吧。首先写两个函数，一个打印奇数，一个打印偶数。（用一个全局变量，交替加1就行。）</p>
<h3 id="3、简述一下socket编程。"><a href="#3、简述一下socket编程。" class="headerlink" title="3、简述一下socket编程。"></a>3、简述一下socket编程。</h3><p>　　socket可以理解成ip+端口，或者说是一组接口。以tcp为例，服务端，创立套接字（socket），绑定ip和端口（bind），监听来自客户端的连接（listen），阻塞至有客户端进行连接请求（accept），连接后直接进行数据传输即可（send，recv）最后关闭套接字。而客户端则需要建立一个同ip及端口的套接字，向服务端发送连接请求（connect），成功后数据交互，关闭套接字。</p>
<h3 id="4、简述一下三次握手和四次挥手。"><a href="#4、简述一下三次握手和四次挥手。" class="headerlink" title="4、简述一下三次握手和四次挥手。"></a>4、简述一下三次握手和四次挥手。</h3><p>画图是特别好理解的，但是面试的话呢，就行不通了，这时候就得想办法组织语言了。</p>
<p><strong>tcp的三次握手</strong></p>
<p>第一次握手：客户端向服务端发起连接请求，同步位SYN=1,seq=x；客户端状态SYN-SENT(同步发送)。</p>
<p>第二次握手：此时服务端接收到请求，状态由listen变为SYN-RECV,并回复应答包SYN=1,ACK=1，ack=x+1，seq=y。</p>
<p>第三次握手：客户端接收到服务端的应答包，向服务端发送确认应答包，ACK=1,ack=y+1，seq=z.</p>
<p><img src="/blog//eidolon_x.gitee.io/blog/2018/10/31/网络编程问题汇总/三次握手.png" alt="图示"></p>
<p><strong>tcp的四次挥手</strong><br>先假设是客户端发起的中断连接请求，这样好描述一些。</p>
<p>第一次挥手：客户端发出连接释放请求FIN=1,seq=x，并停止数据发送，进入FIN-WAIT-1状态。</p>
<p>第二次挥手：服务端收到释放请求后发出确认请求报文段，ACK=1,ack=x+1,seq=y,并进入CLOSE-WAIT状态，此时A-B的连接中断。A接收到B的应答包后，进入FIN-WAIT-2状态。</p>
<p>第三次挥手：客户端没有要发送的数据后，向A发送中断连接请求包，FIN=1,ACK=1,ack=x+1，seq=z。B进入LAST-ACK状态，等待最后的确认。</p>
<p>第四次挥手：服务端收到中断连接包后，发出确认包，ACK=1,seq=y+1，ack=z+1，A进入TIME-WAIT状态，等待2ms后，进入close状态。<br><img src="/blog//eidolon_x.gitee.io/blog/2018/10/31/网络编程问题汇总/四次挥手.png" alt="图示"></p>
<h2 id="常考题型"><a href="#常考题型" class="headerlink" title="常考题型"></a>常考题型</h2><h3 id="static和const的作用"><a href="#static和const的作用" class="headerlink" title="static和const的作用"></a>static和const的作用</h3><h4 id="static作用"><a href="#static作用" class="headerlink" title="static作用"></a>static作用</h4><p>1、隐藏，static修饰的函数，变量只能在本模块内被访问和使用。<br>2、保持变量的持久，在程序被执行时一直存在。<br>3、默认初始化为0，静态存储区中的字节默认值为0x00；<br>拓展：在c++中，类在类声明static变量或函数时：类的静态成员函数或变量属于整个类而非类的对象，没有this指针。 </p>
<blockquote>
<p>静态数据成员初始化的格式：</p>
</blockquote>
<blockquote>
<p><strong>&lt;数据类型&gt; 类名 :: 静态数据成员名 = 值</strong> </p>
</blockquote>
<h4 id="const作用"><a href="#const作用" class="headerlink" title="const作用"></a>const作用</h4><p>表示修饰对象的可读属性。<br>1、修饰变量，阻止变量被改变。<br>2、修饰指针，阻止指针指向或指向的内容被改变。<br>3、修饰函数形参，表明是一个输入参数，在函数过程中不可被改变。<br>4、修饰返回值类型，使其返回值不为左值。（常用于运算符重载）</p>
<h3 id="内存分配"><a href="#内存分配" class="headerlink" title="内存分配"></a>内存分配</h3><p><img src="/blog//eidolon_x.gitee.io/blog/2018/10/31/网络编程问题汇总/高级内存分析.png" alt="图示"></p>
<h3 id="a占空间问题"><a href="#a占空间问题" class="headerlink" title="a占空间问题"></a>a占空间问题</h3><p>int a  　—— a是一个int型变量  4</p>
<p>int *a 　—— a是一个指针，指向一个int型数据 4</p>
<p>int **a　—— a是一个二级指针，指向一个指向int型数据的指针 4</p>
<p>int a[3] —— a是一个有三个int型元素的数组 12</p>
<p>int a[3][4] —— a是一个二维数组，3*4个int型元素 48</p>
<p>char *a[3][4]—— a是一个二维指针数组，有3x4个指向char型数据的指针 48</p>
<p>char （*a）[3][4]—— a是一个数组指针，指针指向一个有3x4个元素的数组。 4</p>
<p>int *a（int，int）—— a是一个返回值是int型指针，有两个int型参数的函数。</p>
<p>int（*a）（int，int）—— a是一个函数指针，指向一个有两个int型参数，返回值为int型的函数。</p>
<h3 id="类似声明与置位题"><a href="#类似声明与置位题" class="headerlink" title="类似声明与置位题"></a>类似声明与置位题</h3><pre><code>给绝对地址0x1000 0000赋值 ——（unsigned int*）0x1000 0000 =1234；

让程序跳转到0x1000 0000运行程序 —— *（（void（*）（）0x1000 0000）（）；//解释，将绝对地址强转成函数指针，然后当作函数指针使用。

将地址为0x1F000010的寄存器指定位n反转：*(（volatile unsigned int*）0x1F000010)^=(0X01&lt;&lt;n)；//同一些寄存器某位，置0——移位与0，置1——移位或1即可。
</code></pre><h3 id="进程与线程的区别与关系"><a href="#进程与线程的区别与关系" class="headerlink" title="进程与线程的区别与关系"></a>进程与线程的区别与关系</h3><p>详情请见：</p>
<p><a href="http://bclnc.github.io/2018/09/20/%E5%AD%A6%E4%B9%A0%E4%B9%8B%E8%B7%AF%20%E2%80%94%E2%80%94%20%E8%BF%9B%E7%A8%8B%E4%B8%8E%E7%BA%BF%E7%A8%8B/" target="_blank" rel="noopener">进程与线程</a></p>
<h3 id="链表题"><a href="#链表题" class="headerlink" title="链表题"></a>链表题</h3><p>详情请见：<br><a href="https://eidolon.xyz/2018/10/19/%E9%93%BE%E8%A1%A8%E6%80%9D%E8%80%83/" target="_blank" rel="noopener">链表</a></p>
<h3 id="结构体和共用体"><a href="#结构体和共用体" class="headerlink" title="结构体和共用体"></a>结构体和共用体</h3><p>struct有字节对齐，所占空间大小要按照字节对齐的原则进行，为所有成员大小之和，union所占空间大小为最大成员大小。</p>
<h3 id="OSI-七层模型"><a href="#OSI-七层模型" class="headerlink" title="OSI    七层模型"></a>OSI    七层模型</h3><p>应、表、会、传、网、数、物。</p>
<p><img src="/blog//eidolon_x.gitee.io/blog/2018/10/31/网络编程问题汇总/OSI.png" alt="OSI"></p>
<h2 id="进程与线程问题"><a href="#进程与线程问题" class="headerlink" title="进程与线程问题"></a>进程与线程问题</h2><h3 id="进程有几种状态，说明他们之间转换可能的事件。"><a href="#进程有几种状态，说明他们之间转换可能的事件。" class="headerlink" title="进程有几种状态，说明他们之间转换可能的事件。"></a>进程有几种状态，说明他们之间转换可能的事件。</h3><p>进程有三种状态，分别是就绪，执行，阻塞。</p>
<p>1、就绪-&gt;执行，进程调度程序为就绪进程分配资源，转变为执行态。<br>2、执行-&gt;就绪，时间片用完，退出执行态，转换成就绪态。<br>3、执行-&gt;阻塞，正在执行的程序因等待某事件无法继续执行时，由执行转阻塞。<br>4、阻塞-&gt;就绪，阻塞态所等待的某事件发生，由阻塞转就绪。</p>
<p>注意——阻塞不会转执行，因为系统调度只会从就绪队列中选择执行项目。</p>
<p>注意——就绪态没有执行，谈不上进入阻塞态</p>
<p>！<a href="进程状态.png">进程状态</a></p>
<h3 id="孤儿进程和僵尸进程"><a href="#孤儿进程和僵尸进程" class="headerlink" title="孤儿进程和僵尸进程"></a>孤儿进程和僵尸进程</h3><p><strong>孤儿进程</strong>：<code>父进程退出，子进程还在运行</code>，那这些子程序就将成为孤儿进程，被init进程（进程号为1）所收养，并由init进程对他们完成状态收集工作。//还是会被回收的，没啥危害。<br><strong>僵尸进程</strong>：<code>一个进程的子进程退出，而父进程并没有调用wait或waitpid获取子进程的状态信息</code>，那么子进程的进程描述符仍然保存在系统中，被称为僵尸进程。//危害，进程号有限，不回收会占用进程号，浪费资源。</p>
<p>进程类型：<br>进程可以分成系统进程和用户进程，系统进程是root用户都无法干涉的进程。而用户进程可以分为：</p>
<p>(1) <code>交互进程</code>：由一个shell终端启动的进程，在执行过程中，需要与用户进行交互操作，可以运行于前台，也可以运行在后台。<br>(2) <code>批处理进程</code>：该进程是一个进程集合，负责按顺序启动其他的进程。<br>(3) <code>守护进程</code>：守护进程是一直运行的一种进程，经常在linux系统启动时启动，在系统关闭时终止。它们独立于控制终端并且周期性的执行某种任务或等待处理某些发生的事件。例如httpd进程，一直处于运行状态，等待用户的访问。还有经常用的crond进程，这个进程类似与windows的计划任务，可以周期性的执行用户设定的某些任务。</p>
<h2 id="就面试所遇问题分析"><a href="#就面试所遇问题分析" class="headerlink" title="就面试所遇问题分析"></a>就面试所遇问题分析</h2><p><strong>1、共享内存怎么解决多个进程同时对其读写导致数据异常的情况？</strong></p>
<p>回答：使用信号量的pv操作，对共享内存进行锁定，使其某一进程在操作时，其他进程无法对其进行操作，实现互斥功能。</p>
<p>接着问，还有什么（读写锁），什么读写锁（互斥锁）。</p>
<p>我是不知道怎么回答，因为确实没有深入的研究这个东西，回复也是凭感觉瞎猜，所以还是要加深学习，看着还是有点头痛的，先未完待续啊。码住，下次接着写。</p>
<p><code>待补充</code>：进程间对资源的互斥访问有条件变量，信号量，读写锁，自旋锁和原子锁。</p>
<p><strong>2、一个无限大的十进制数转化为16进制，最后两位是什么？</strong></p>
<p>回答：当时没回答上来，有点蠢了，其实脑子里想到了转为2进制，没表达清楚，想的是与0xff相与，剩下的就是需要的数了。当时蠢得可怕，蠢得可怕！</p>
<p><strong>3、用二分查找法查找一个有序数列中没有的数，会循环多少次？</strong><br>回答：这个序列的个数小于2的n+1次幂，大于2的n次幂，则这个n为循环次数。<br>再问如何优化算法。其实二分查找就是一个树，查找的次数就是树的高度，查找的次数就是log2n，取整。哇，自己是真的捞啊！</p>
<p>还有问到sqrt函数的时间复杂度，什么是时间复杂度，到时候再开一个博文详细解释吧。还有索引，和数据库有关，一时半会儿讲不清楚，就不细写了。遇到问思路的面试官一定不能紧张，多想想，多给自己一些时间。</p>

      
    </div>
    
    
    
	
	<div>
	  
		<div>
    
        <div style="text-align:center;color: #ccc;font-size:14px;">------ 本文结束------</div>
    
</div>
	  
	</div>
	

    

    

    
      <div>
        <ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者：</strong>
    喵呜  |  喵呜
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="http://eidolon_x.gitee.io/blog/2018/10/31/网络编程问题汇总/" title="笔试常见问题汇总">http://eidolon_x.gitee.io/blog/2018/10/31/网络编程问题汇总/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>
    本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/3.0/" rel="external nofollow" target="_blank">CC BY-NC-SA 3.0</a> 许可协议。转载请注明出处！
  </li>
  <li class="post-copyright-license">
    并保留本声明和上方二维码。感谢您的阅读和支持！
  </li>
</ul>
      </div>
    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/blog/tags/笔试常见问题汇总/" rel="tag"># 笔试常见问题汇总</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/blog/2018/10/25/字符串操作/" rel="next" title="字符串操作">
                <i class="fa fa-chevron-left"></i> 字符串操作
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/blog/2018/11/20/ARM随记/" rel="prev" title="ARM随记">
                ARM随记 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/blog/images/1.jpg"
                alt="喵呜" />
            
              <p class="site-author-name" itemprop="name">喵呜</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/blog/archives/">
              
                  <span class="site-state-item-count">20</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/blog/categories/index-1.html">
                  <span class="site-state-item-count">5</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

			
			  <div class="site-state-item site-state-tags">
				<a href="/blog/tags/ || tags">
				  <span class="site-state-item-count">13</span>
				  <span class="site-state-item-name">标签</span>
				</a>
			  </div>
			

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/blog/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#小感慨"><span class="nav-text">小感慨</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#网络编程的常见问题"><span class="nav-text">网络编程的常见问题</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1、TCP和UDP的区别。"><span class="nav-text">1、TCP和UDP的区别。</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2、多线程是怎么实现同步的。"><span class="nav-text">2、多线程是怎么实现同步的。</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3、简述一下socket编程。"><span class="nav-text">3、简述一下socket编程。</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#4、简述一下三次握手和四次挥手。"><span class="nav-text">4、简述一下三次握手和四次挥手。</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#常考题型"><span class="nav-text">常考题型</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#static和const的作用"><span class="nav-text">static和const的作用</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#static作用"><span class="nav-text">static作用</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#const作用"><span class="nav-text">const作用</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#内存分配"><span class="nav-text">内存分配</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#a占空间问题"><span class="nav-text">a占空间问题</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#类似声明与置位题"><span class="nav-text">类似声明与置位题</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#进程与线程的区别与关系"><span class="nav-text">进程与线程的区别与关系</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#链表题"><span class="nav-text">链表题</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#结构体和共用体"><span class="nav-text">结构体和共用体</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#OSI-七层模型"><span class="nav-text">OSI    七层模型</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#进程与线程问题"><span class="nav-text">进程与线程问题</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#进程有几种状态，说明他们之间转换可能的事件。"><span class="nav-text">进程有几种状态，说明他们之间转换可能的事件。</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#孤儿进程和僵尸进程"><span class="nav-text">孤儿进程和僵尸进程</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#就面试所遇问题分析"><span class="nav-text">就面试所遇问题分析</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      
        <div class="back-to-top">
          <i class="fa fa-arrow-up"></i>
          
        </div>
      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">喵呜</span>

  
</div>

<div>
<script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>
<span id="busuanzi_container_site_pv" style='display:none'>
    本站总访问量 <span id="busuanzi_value_site_pv"></span> 次
    <span class="post-meta-divider">|</span>
</span>
<span id="busuanzi_container_site_uv" style='display:none'>
    有<span id="busuanzi_value_site_uv"></span>人看过我的博客啦
</span>
</div>


  <div class="powered-by">QQ  母胎solo </div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">微信：请勿撩骚 &mdash;  v5.1.4</div>




        







        
      </div>
    </footer>

    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  


  











  
  
    <script type="text/javascript" src="/blog/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/canvas-nest/canvas-nest.min.js"></script>
  


  


  <script type="text/javascript" src="/blog/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/blog/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/blog/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/blog/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/blog/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/blog/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("C4C53NNHHx80rdEcr9XGvVER-gzGzoHsz", "onx6D9nlRn56BhlHoI3E08PQ");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  

  
  

  

  

  
  <script type="text/javascript" src="/blog/js/src/exturl.js?v=5.1.4"></script>


  <!-- 页面点击小红心 -->
<script type="text/javascript" src="/js/src/love.js"></script>

</body>
</html>
